<template>
  <!-- 上传图片 -->
  <div class="upload-page-container">
    <el-upload
        ref="uploadImage"
        action="/adminapi/common/upload/file"
        name="file"
        list-type="picture-card"
        :file-list="fileList"
        :on-preview="handlePictureCardPreview"
        :limit="limit"
        :on-success="handleAvatarSuccess"
        :on-remove="handleAcatarRemove"
        :headers="{'authentication': loginToken, 'x-header-client': 'WLTX-ADMIN-API'}">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        append-to-body>
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
  </div>
</template>
<script>
import $storage from '@/utils/storage.js'

export default {
  name: 'UploadImageFile',
  props: {
    limit: {
      type: Number,
      default: ()=> 1
    },
    uploadValue: {
      type: Array,
      default: ()=> []
    }
  },
  computed: {
    fileList: {
      get() {
        let showImages = []
        this.uploadValue.forEach(item=> {
          showImages.push({ url: item })
        })
        return showImages
      }
    }
  },
  data() {
    return {
      loginToken: $storage.getUserToken(),
      dialogVisible: false,
      dialogImageUrl: ''
    }
  },
  methods: {
    // 选择文件上传成功
    async handleAvatarSuccess(res){
      if(!res.data) this.$message.error('上传失败')
      let showImageList = this.uploadValue
      showImageList.push(res.data.url)
      this.$emit('update:uploadValue', showImageList)
      this.uploadChange()
    },

    async handleAcatarRemove(file, fileList){
      let showImageList = []
      fileList.forEach(item=> {
        showImageList.push(item.url)
      })
      this.$emit('update:uploadValue', showImageList)
      this.uploadChange()
    },

    // 预览图片
    handlePictureCardPreview(file){
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

    // 添加change事件
    async uploadChange(){
      this.$emit('uploadChange')
    }
  }
}
</script>
<style lang="scss" scoped>
  .upload-page-container {
    width: 100%;

    ::v-deep .avatar-uploader {

      .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        width: 150px;
        height: 150px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }

      .el-upload:hover {
        border-color: #409EFF;
      }

      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 128px;
        height: 128px;
        line-height: 128px;
        text-align: center;
      }
    }
  }
</style>